<?php
include ("XML_Serializer/Unserializer.php");

class Query {

  var $function;
  var $parameters;
  
  // Parses a get variable of the format a/b/c/d 
  // into an object
  function parse( $q, $separator = '/' ) {
    // if q isn't a string, return it
    if( !is_string($q) ) {
      die( "Invalid input into parseQ" );
    }
    
    // turn it into an array
    $elements = explode( $separator, $q );
    
    // the last element is always the function to call
    $function = array_pop( $elements );
    
    // If we have an odd number of elements
    // left after removing the function then
    // the q string is bad and we can't make
    // key=>value pairs
    if( count( $elements ) % 2 != 0 ) {
      die( "Invalid q string!" );
    }
    
    // Transform the array into a hash were evens 
    $paramArray = array();
    for( $i = 0; $i < count( $elements ); $i += 2 ) {
      if( $elements[$i] && $elements[$i+1] ) {
        $paramArray[$elements[$i]] = $elements[$i+1];
      }
    }
    
    $this->function = $function;
    $this->parameters = $paramArray;
  }
}

###############################################################################
#
# Global functions
#
###############################################################################

function testQuery( $parameters ) {
  return json_encode($parameters);
}

function available( $parameters ) {
  eval(file_get_contents('config.pl'));
  if( $parameters['hostname'] ) {
    $hostname = $parameters['hostname'];
  }
  else {
    $hostname = $fqdn;
  }
  $options = array(
    'parseAttributes' => true
  );
  $unserializer = &new XML_Unserializer($options);
  if( $returnObj = $unserializer->unserialize( "http://". $hostname ."/index.xml", true ) === true ) {
    return json_encode($unserializer->getUnserializedData());
  }
  else {
    $error = Array (
      "message" => "Could not fetch index.xml from ". $hostname
    );
    return json_encode($error);
  }
}

function unprocessed( $parameters ) {
  eval(file_get_contents('config.pl'));
  if( is_dir($raw) ) {
    if( $dh = opendir( $raw ) ) {
      while( ( $file = readdir( $dh ) ) !== false ) {
        if( $file == '.' || $file == '..' || strpos($file,'.zip') === false )
          continue;
        $zips[] = $raw .'/'. $file;
      }
      closedir( $dh );
      if( count( $zips ) < 1 ) {
        return '<return>No unprocessed files found.</return>';
      }
      else {
        return json_encode($zips);
      }
    }
  }
}

###############################################################################
#
# Actual incoming handling here
#
###############################################################################

if( $_GET['q'] ) {
  $myQuery = new Query();
  $myQuery->parse( $_GET['q'] );
  if( is_callable( $myQuery->function ) ) {
    $functionName = $myQuery->function;
    $json = $functionName( $myQuery->parameters );
    echo $json;
    die();
  }
}
?>
